﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using log4net;
using log4net.Config;
using WebMatrix.WebData;

namespace BHS.Business.Logging
{
    public sealed class UserAgentLog
    {
        #region privates

        private const string logSectionName = "BHS_Agent_Logs_";
        private static readonly UserAgentLog instance = new UserAgentLog();
        private readonly Log4NetWrapLogger iLog;

        #endregion

        private UserAgentLog()
        {
            ConfigureLogging();
            iLog = new Log4NetWrapLogger(LogManager.GetLogger(logSectionName));
        }

        #region business

        /// <summary>
        /// Return logger its log data to file
        /// </summary>
        /// <returns></returns>
        public static ILog Service
        {
            get { return instance.iLog; }
        }

        private static void ConfigureLogging()
        {
            var configSource = new StringBuilder();
            configSource.Append("<log4net>");
            configSource.Append("  <appender name=\"RollingFile\" type=\"log4net.Appender.RollingFileAppender\">");
            configSource.Append("    <param name=\"File\" value=\"C:\\Logs\\BHS_Agent_Logs_\" />");
            configSource.Append("    <param name=\"AppendToFile\" value=\"true\" />");
            configSource.Append("    <param name=\"MaxSizeRollBackups\" value=\"10\" />");
            configSource.Append("    <param name=\"MaximumFileSize\" value=\"1024KB\" />");
            configSource.Append("    <param name=\"RollingStyle\" value=\"Composite\" />");
            configSource.Append("    <param name=\"DatePattern\" value=\"yyyy-MM-dd.\\lo\\g\" />");
            configSource.Append("    <param name=\"StaticLogFileName\" value=\"false\" />");

            configSource.Append("    <lockingModel type=\"log4net.Appender.FileAppender+MinimalLock\" />");
            configSource.Append("    <layout type=\"log4net.Layout.PatternLayout\">");
            configSource.Append(
                "      <param name=\"ConversionPattern\" value=\"%d{HH:mm:ss} %-5p [%logger] %m%newline\" />");
            configSource.Append("    </layout>");
            configSource.Append("  </appender>");
            configSource.Append("  <root>");
            configSource.Append("    <level value=\"ALL\" />");
            configSource.Append("    <appender-ref ref=\"RollingFile\" />");
            configSource.Append("  </root>");
            configSource.Append("</log4net>");

            var output = new MemoryStream();
            var writer = new StreamWriter(output);
            writer.Write(configSource);
            writer.Flush();
            output.Position = 0;
            XmlConfigurator.Configure(output);
            output.Close();
        }

        #endregion
    }

}
